package com.spzx.product.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.domain.Category;
import com.spzx.product.handler.CategoryExcelDateReadListener;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.CategoryService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {
    @Resource
    @Lazy
    private CategoryExcelDateReadListener categoryExcelDateReadListener;

    @Override
    public List<Category> listInfo(Long parentId) {
        List<Category> categoryList = baseMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getParentId, parentId));
        if (!CollectionUtils.isEmpty(categoryList)) {
            for (Category category : categoryList) {
                category.setHasChildren(baseMapper.selectCount(new LambdaQueryWrapper<Category>().eq(Category::getParentId, category.getId())) > 0);
            }
            return categoryList;
        }
        return null;
    }

    @Override
    public void exportCategory(HttpServletResponse response) {
        //1、查询所有的分类数据
        List<Category> categoryList = list();
        //设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //3、将数据写入到excel文件中
        try {
            EasyExcel.write(response.getOutputStream(), Category.class)
                    //工作簿
                    .sheet("分类数据")
                    //表头
                    .doWrite(categoryList);
        } catch (Exception e) {
            throw new ServiceException("导出分类数据失败");
        }
    }

    @Override
    public boolean importCategory(MultipartFile file) {
        //1、判断文件是否为空
        if (!file.isEmpty()) {
            //2、判断文件名
            String filename = file.getOriginalFilename();
            if (filename != null) {
                if (!filename.endsWith(".xlsx") && !filename.endsWith(".xls") && !filename.endsWith(".png")) {
                    throw new ServiceException("文件格式不正确");
                }
                //3、读取excel文件中的数据
                try {
                    EasyExcel.read(file.getInputStream())
                            .head(Category.class)
                            .sheet(0)
                            .registerReadListener(categoryExcelDateReadListener)
                            .doRead();
                    return true;
                } catch (Exception e) {
                    throw new ServiceException("导入分类数据失败");
                }
            }
        }
        return false;
    }

    @Override
    public boolean checkCategoryUnique(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getId, category.getId());
        queryWrapper.or(q->q.eq(Category::getParentId,category.getParentId()).eq(Category::getName, category.getName()));
         baseMapper.selectCount(queryWrapper);
        return baseMapper.selectCount(queryWrapper)> 0;
    }

    @Override
    public List<Category> listCategoryTree() {
        List<Category> categories = list(new LambdaQueryWrapper<Category>().eq(Category::getParentId, 0));
        buildCategoryTree(categories);
        return categories;
    }

    private void buildCategoryTree(List<Category> categories) {
        if (!CollectionUtils.isEmpty(categories)) {
            categories.forEach(category -> {
                List<Category> children = list(new LambdaQueryWrapper<Category>().eq(Category::getParentId, category.getId()));
               if (!CollectionUtils.isEmpty(children)){
                    category.setChildren(children);
                    buildCategoryTree(children);
                }
            });
        }
    }
}




